package com.zj.system.service.impl;

import com.seventh.common.pojo.R;
import com.seventh.common.utils.JwtUtils;


import com.zj.system.config.RsaKeyProperties;
import com.zj.system.pojo.entity.User;
import com.zj.system.pojo.vo.LoginVo;
import com.zj.system.service.LoginSer;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @program: clms-seventh
 * @description: 登陆的逻辑层
 * @author: 张静
 * @create: 2021-07-16 20:11
 **/
@Service
public class LoginSerImpl implements LoginSer {
    @Autowired
    private RsaKeyProperties rsaKeyProperties;

    @Override
    public R login(LoginVo vo) {
        Subject subject= SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken=new UsernamePasswordToken(vo.getUsername(),vo.getPassword());
        try{
            subject.login(usernamePasswordToken);//自动调用Realm认证器
            User u = (User) subject.getPrincipal();
            User user=new User();
            user.setUserName(vo.getUsername());
            user.setUserId(u.getUserId());
            user.setUserName(u.getUserName());
            user.setAvatar(u.getAvatar());
            user.setLoginName(u.getLoginName());

            String token=JwtUtils.generateTokenExpireInMinutes(user, rsaKeyProperties.getPrivateKey(), 24 * 60);

            return R.ok().put("token",token);
        }catch (Exception e){
            e.printStackTrace();
            return R.error();
        }
    }

    @Override
    public R solvtoken(String token) {

        return R.ok().put("userinfomation",JwtUtils.getInfoFromToken(token, rsaKeyProperties.getPublicKey(), User.class));
    }
}
